/*
 * FormAvaliacao.java
 *
 * Created on 29 de Outubro de 2008, 17:03
 */
package br.com.radaction.gui;

import br.com.radaction.DAO.AvaliacaoDAO;
import br.com.radaction.DAO.DisciplinaDAO;
import br.com.radaction.DTO.Avaliacao;
import br.com.radaction.DTO.Disciplina;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * Esta Classe é uma implementação GUI para mostrar avaliações cadastradas pelo aluno.
 * @author  robson
 */
public class FormAvaliacao extends javax.swing.JInternalFrame {

    private JFrame mdi;

    /** Construtor, cria um novo formulário FormAvaliacao */
    public FormAvaliacao(JFrame mdi) {
        this.mdi = mdi;
        initComponents();
        this.atualizaLista();
    }

    /**
     * Este método atualiza a grade de avaliações
     * É um método sem retorno
     */
    private void atualizaLista() {
        try {
            AvaliacaoDAO avDAO = new AvaliacaoDAO(MDIAcademics.getConexao());
            List<Avaliacao> lista = avDAO.listaTodos();
            DefaultTableModel dtm = (DefaultTableModel) this.tbAvaliacao.getModel();
            dtm.setRowCount(0);
            for (Avaliacao av : lista) {
                String concluida;
                if (av.getFlgConcluida()) {
                    concluida = "V";
                } else {
                    concluida = "F";
                }
                String dia = null;
                int iDia = av.getData().getDay();
                switch (iDia) {
                    case (0):
                        dia = "Dom";
                        break;
                    case (1):
                        dia = "Seg";
                        break;
                    case (2):
                        dia = "Ter";
                        break;
                    case (3):
                        dia = "Qua";
                        break;
                    case (4):
                        dia = "Qui";
                        break;
                    case (5):
                        dia = "Sex";
                        break;
                    case (6):
                        dia = "Sáb";
                        break;
                }
                int mes = av.getData().getMonth() + 1;
                dia += " - " + av.getData().getDate() + "/" + mes;
                dtm.addRow(new Object[]{av.getCod(), dia, av.getTarefa(), av.getDisciplina(), concluida});

            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler as Avaliacoes:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler as Avaliacoes", ex);
        }
    }

    /**
     * Método que busca através do DAO as disciplinas no banco de dados e
     * carrega no ComboBox
     * É um método sem retorno
     */
    private void carregaCmbDisciplina() {
        try {
            DisciplinaDAO dDAO = new DisciplinaDAO(MDIAcademics.getConexao());
            List<Disciplina> lista = dDAO.listaTodos();
            Vector v = new Vector(lista);
            v.add(0, "");
            ComboBoxModel cbm = new DefaultComboBoxModel(v);
            this.cmbDisciplina.setModel(cbm);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler as Disciplinas:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler as Disciplinas", ex);
        }
    }

    /**
     * Preenche os campos da tela com informações das avaliações. 
     * @param av Avaliacao que irá fornecer o código para pesquisa no SGBD e em seguida ir para a tela.
     */
    private void preencheTela(Avaliacao av) {
        try {
            AvaliacaoDAO avDAO = new AvaliacaoDAO(MDIAcademics.getConexao());
            av = avDAO.retrieve(av);
            if (av != null && av.getCod() > 0) {
                this.txtCodigo.setText(Integer.toString(av.getCod()));
                this.txtTarefa.setText(av.getTarefa());
                this.txtDescricaoAv.setText(av.getDescricao());
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                this.txtData.setText(sdf.format(av.getData()));
                this.cmbDisciplina.setSelectedItem(av.getDisciplina());
                this.chkConcluida.setSelected(av.getFlgConcluida());

            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Não foi possível carregar Avaliacao: %s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Método auxiliar para converter valores String sem causar exceções.
     * @param valor String contendo o valor a ser transformado para número
     * @return O valor convertido em inteiro ou zero em caso de algum problema
     */
    private int intCampoTelas(String valor) {
        int ret = 0;
        try {
            ret = Integer.parseInt(valor);
        } catch (NumberFormatException ex) {
        }
        return ret;
    }

    /**
     * Método auxiliar que limpa todos os campos da GUI
     */
    private void limpaTela() {
        this.txtCodigo.setText(null);
        this.txtData.setText(null);
        this.txtDescricaoAv.setText(null);
        this.txtTarefa.setText(null);
        this.cmbDisciplina.setSelectedIndex(0);
        this.txtCodigo.requestFocus();
        if (this.chkConcluida.isSelected()) {
            this.chkConcluida.setSelected(false);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        gpEstado = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescricaoAv = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbAvaliacao = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        txtTarefa = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cmbDisciplina = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        txtData = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        chkConcluida = new javax.swing.JCheckBox();
        btAtualiza = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        txtDataInicial = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtDataFinal = new javax.swing.JFormattedTextField();
        btFiltra = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        btSalva = new javax.swing.JButton();
        btLimpa = new javax.swing.JButton();
        btExclui = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastro - Avaliações");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameDeiconified(evt);
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Observações"));

        txtDescricaoAv.setColumns(20);
        txtDescricaoAv.setLineWrap(true);
        txtDescricaoAv.setRows(5);
        txtDescricaoAv.setToolTipText("Observações");
        txtDescricaoAv.setWrapStyleWord(true);
        jScrollPane2.setViewportView(txtDescricaoAv);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)
                .addContainerGap())
        );

        tbAvaliacao.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod.", "Data", "Tarefa", "Disciplina", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbAvaliacao.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbAvaliacaoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbAvaliacao);
        tbAvaliacao.getColumnModel().getColumn(0).setMinWidth(20);
        tbAvaliacao.getColumnModel().getColumn(0).setMaxWidth(44);
        tbAvaliacao.getColumnModel().getColumn(1).setMinWidth(120);
        tbAvaliacao.getColumnModel().getColumn(1).setMaxWidth(130);
        tbAvaliacao.getColumnModel().getColumn(2).setMinWidth(300);
        tbAvaliacao.getColumnModel().getColumn(2).setMaxWidth(300);
        tbAvaliacao.getColumnModel().getColumn(3).setMinWidth(180);
        tbAvaliacao.getColumnModel().getColumn(4).setMinWidth(20);
        tbAvaliacao.getColumnModel().getColumn(4).setMaxWidth(44);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados da Tarefa"));

        jLabel5.setText("Código:");

        jLabel2.setText("Nome:");

        txtCodigo.setEditable(false);
        txtCodigo.setToolTipText("O código é automático");
        txtCodigo.setEnabled(false);
        txtCodigo.setOpaque(false);
        txtCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCodigoFocusLost(evt);
            }
        });

        txtTarefa.setToolTipText("Nome da tarefa");

        jLabel1.setText("Disciplina:");

        cmbDisciplina.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbDisciplina.setToolTipText("Selecione a Disciplina");

        jLabel4.setText("Data:");

        txtData.setToolTipText("dd/mm/aaaa");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Estado:"));

        chkConcluida.setText("Concluída");
        chkConcluida.setToolTipText("Já terminou a tarefa?");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chkConcluida)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(chkConcluida)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2))
                .addGap(12, 12, 12)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cmbDisciplina, 0, 307, Short.MAX_VALUE)
                    .addComponent(txtTarefa, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(7, 7, 7))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(txtTarefa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btAtualiza.setText("Atualizar");
        btAtualiza.setToolTipText("Atualiza a lista");
        btAtualiza.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAtualizaActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        txtDataInicial.setColumns(10);
        txtDataInicial.setToolTipText("Data inicial (dd/mm/aaaa)");

        jLabel3.setText("Período:");

        jLabel6.setText("a");

        txtDataFinal.setToolTipText("Data final (dd/mm/aaaa)");

        btFiltra.setText("Filtrar");
        btFiltra.setToolTipText("Filtar lista por período");
        btFiltra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFiltraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(btFiltra, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtDataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btFiltra))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btSalva.setText("Salvar");
        btSalva.setToolTipText("Salvar novo registro");
        btSalva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvaActionPerformed(evt);
            }
        });

        btLimpa.setText("Limpar");
        btLimpa.setToolTipText("Limpar campos");
        btLimpa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimpaActionPerformed(evt);
            }
        });

        btExclui.setText("Excluir");
        btExclui.setToolTipText("Excluir registro");
        btExclui.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluiActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btSalva, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btLimpa, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btExclui, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btExclui)
                    .addComponent(btLimpa)
                    .addComponent(btSalva))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(68, 68, 68)
                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btAtualiza)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btAtualiza))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        jPanel2.getAccessibleContext().setAccessibleName("Dados da Avaliação");

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
    this.carregaCmbDisciplina();
}//GEN-LAST:event_formInternalFrameOpened

private void tbAvaliacaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbAvaliacaoMouseClicked
    if (evt.getClickCount() > 0) {
        JTable obj = (JTable) evt.getComponent();
        int linha = obj.getSelectedRow();
        Integer cod = (Integer) obj.getModel().getValueAt(linha, 0);
        Avaliacao av = new Avaliacao(cod);
        this.preencheTela(av);
    }
}//GEN-LAST:event_tbAvaliacaoMouseClicked

private void txtCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCodigoFocusLost
    int cod = this.intCampoTelas(this.txtCodigo.getText());
    if (cod > 0) {
        Avaliacao av = new Avaliacao(cod);
        this.preencheTela(av);
    }
}//GEN-LAST:event_txtCodigoFocusLost

private void btLimpaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimpaActionPerformed
    this.limpaTela();
    this.carregaCmbDisciplina();
}//GEN-LAST:event_btLimpaActionPerformed

private void btSalvaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvaActionPerformed
    try {
        Avaliacao av = new Avaliacao();
        av.setTarefa(txtTarefa.getText().toUpperCase());
        av.setDescricao(txtDescricaoAv.getText().toUpperCase());
        //obj recebe o um Object selecionado no cmbBox
        Object obj = this.cmbDisciplina.getModel().getSelectedItem();
        //abaixo o Object obj é testado se é um objeto Disciplina, se for é 
        //setado para av Avaliacao
        if (obj instanceof Disciplina) {
            av.setDisciplina((Disciplina) obj);
        } else {
            JOptionPane.showMessageDialog(this.mdi, "Disciplina deve ser informada");
            this.cmbDisciplina.requestFocus();
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        av.setData(sdf.parse(this.txtData.getText()));
        av.setConcluida(chkConcluida.isSelected());
        AvaliacaoDAO avDao = new AvaliacaoDAO(MDIAcademics.getConexao());
        int cod = this.intCampoTelas(this.txtCodigo.getText());
        // Escolhe entre atualizar ou criar
        if (cod > 0) {
            av.setCod(cod);
            avDao.update(av);
        } else {
            avDao.create(av);
            this.txtCodigo.setText(Integer.toString(av.getCod()));
        }

        JOptionPane.showMessageDialog(this.mdi, "Registro Salvo");
        this.limpaTela();
        this.carregaCmbDisciplina();
        this.atualizaLista();
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(this.mdi, "Número mal formatado [Código]");
        this.txtCodigo.requestFocus();
    } catch (ParseException ex) {
        JOptionPane.showMessageDialog(this.mdi, "Data inválida");
        this.txtData.requestFocus();
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao gravar Avaliacao:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FormAvaliacao.class.getName()).log(Level.SEVERE, null, ex);
    }
}//GEN-LAST:event_btSalvaActionPerformed

private void btExcluiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluiActionPerformed
    try {
        int cod = this.intCampoTelas(this.txtCodigo.getText());
        if (cod > 0) {
            Avaliacao av = new Avaliacao(cod);
            AvaliacaoDAO avDAO = new AvaliacaoDAO(MDIAcademics.getConexao());
            avDAO.delete(av);
            this.limpaTela();
            this.atualizaLista();
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao excluir Avaliacao:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao excluir Avaliacao", ex);
    }
}//GEN-LAST:event_btExcluiActionPerformed

private void btAtualizaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAtualizaActionPerformed
    this.atualizaLista();
    this.carregaCmbDisciplina();
    this.limpaTela();
}//GEN-LAST:event_btAtualizaActionPerformed

private void formInternalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameDeiconified
    this.atualizaLista();
    this.carregaCmbDisciplina();
}//GEN-LAST:event_formInternalFrameDeiconified

private void btFiltraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFiltraActionPerformed
    this.atualizaLista(this.txtDataInicial.getText(), this.txtDataFinal.getText());
}//GEN-LAST:event_btFiltraActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAtualiza;
    private javax.swing.JButton btExclui;
    private javax.swing.JButton btFiltra;
    private javax.swing.JButton btLimpa;
    private javax.swing.JButton btSalva;
    private javax.swing.JCheckBox chkConcluida;
    private javax.swing.JComboBox cmbDisciplina;
    private javax.swing.ButtonGroup gpEstado;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tbAvaliacao;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtData;
    private javax.swing.JFormattedTextField txtDataFinal;
    private javax.swing.JFormattedTextField txtDataInicial;
    private javax.swing.JTextArea txtDescricaoAv;
    private javax.swing.JTextField txtTarefa;
    // End of variables declaration//GEN-END:variables

    private void atualizaLista(String dataInicial, String dataFinal) {
        try {
            AvaliacaoDAO avDAO = new AvaliacaoDAO(MDIAcademics.getConexao());
            List<Avaliacao> lista = avDAO.listaTodos(dataInicial, dataFinal);
            DefaultTableModel dtm = (DefaultTableModel) this.tbAvaliacao.getModel();
            dtm.setRowCount(0);
            for (Avaliacao av : lista) {
                String concluida;
                if (av.getFlgConcluida()) {
                    concluida = "V";
                } else {
                    concluida = "F";
                }
                String dataEntrega = null;
                switch (av.getData().getDay()) {
                    case (0):
                        dataEntrega = "Dom";
                        break;
                    case (1):
                        dataEntrega = "Seg";
                        break;
                    case (2):
                        dataEntrega = "Ter";
                        break;
                    case (3):
                        dataEntrega = "Qua";
                        break;
                    case (4):
                        dataEntrega = "Qui";
                        break;
                    case (5):
                        dataEntrega = "Sex";
                        break;
                    case (6):
                        dataEntrega = "Sáb";
                        break;
                }
                int mes = av.getData().getMonth() + 1;
                dataEntrega += " - " + av.getData().getDate() + "/" + mes;
                dtm.addRow(new Object[]{av.getCod(), dataEntrega, av.getTarefa(), av.getDisciplina(), concluida});
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler as Avaliacoes:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler as Avaliacoes", ex);
        }
    }
}
